# Title     : TODO
# Objective : TODO
# Created by: yz
# Created on: 2018/3/1

library(optparse)
library(magrittr)
library(viridis)
library(xlsx)
library(tidyverse)
option_list <- list(
  make_option("--base", default = "metabo_base.R", type = "character", help = "metabo base R file")
)
opt <- parse_args(OptionParser(option_list = option_list))

fileName <- "name_map.txt"

if (!file.exists(fileName)) {
  quit(status = 0)
}

nameMapDf <- read_tsv(fileName)

keggIds <- nameMapDf$KEGG
if (all(is.na(keggIds))) {
  quit(status = 0)
}

data <- read_csv("Pathway_Result.csv") %>%
  rename(Metabolite = X1)

head(data)

plotData <- data %>%
  rename(p = `Raw P`) %>%
  mutate(p = as.numeric(p), Impact = as.numeric(Impact)) %>%
  mutate(logP = -log(p)) %>%
  arrange(logP) %>%
  mutate(Metabolite = factor(Metabolite, levels = unique(Metabolite))) %>%
  filter(Impact > 0)

height <- max(2 + (nrow(plotData) - 10) * 0.15, 2) + 2

plotData %>% as.data.frame()
str(plotData)

parent <- "./"
p <- ggplot(plotData, mapping = aes(x = Metabolite, y = Impact)) +
  ylab("Impact") +
  xlab("") +
  theme_bw(base_size = 8.8, base_family = "Times") +
  theme(axis.text.x = element_text(size = 10, hjust = 1, vjust = 1), legend.position = 'right',
        legend.text = element_text(size = 9), legend.title = element_text(size = 11), axis.text.y = element_text(size = 10),
        axis.title.y = element_text(size = 11), axis.title.x = element_text(size = 12), panel.grid.major.x = element_blank(),
        panel.border = element_rect(size = 0.75), panel.grid.minor.x = element_blank(), panel.grid.major.y = element_blank(),
  ) +
  geom_col(aes(fill = logP)) +
  coord_flip() +
  scale_fill_gradient("-ln(P)", low = "yellow", high = "red")

pdfFileName <- paste0(parent, "/Pathway_Barplot.pdf")
ggsave(limitsize = FALSE, pdfFileName, p, width = 6, height = height)







